package com.xiao.hao.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xiao.hao.constant.NumberConstants;
import com.xiao.hao.constant.UserTokenParams;
import com.xiao.hao.exception.AuthException;
import com.xiao.hao.utils.RedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @Desciption:
 * @Author: 郑焱军
 * @Date: 2022/9/21 19:29
 */
@Component
@Aspect
public class ControllerAop {

    @Resource
    RedisUtil redisUtil;


    /**
     * 过程控制器
     *
     * @param joinPoint 连接点
     * @return {@link Object}
     * @throws Throwable throwable
     */
    @Around("execution(* com.xiao.hao.controller.auth.*Controller.*(..))")
    public Object processController(ProceedingJoinPoint joinPoint) throws Throwable {
        String authorization = UserConfig.getToken();
        AuthException.isTrue(StrUtil.isNotEmpty(authorization), "非法请求");
        Object proceed = null;
        try {
            Object json = redisUtil.get(NumberConstants.TOKEN_PRE + authorization);
            AuthException.isTrue(ObjectUtil.isNotEmpty(json), "登录已过期,请重新登录！！！");
            UserTokenParams userTokenParams = JSONUtil.toBean((String) json,
                    UserTokenParams.class);
            redisUtil.set(NumberConstants.TOKEN_PRE + authorization, JSONUtil.toJsonStr(userTokenParams)
                    , 7200);
            RequestDataHelper.setRequestData(new HashMap<String, Object>() {{
                put("userName", userTokenParams.getUserName());
                put("userId", userTokenParams.getUserId());
            }});
            proceed = joinPoint.proceed();
        } finally {
            RequestDataHelper.removeRequest();
        }
        return proceed;
    }

}
